#include "HttpServer.hpp"
#include <memory>
#include <fstream>
#include "Util.hpp"

static const int BUFFER_SIZE = 1024;

#define ROOT "./rootwww"
#define HOMEPAGE "index.html"

void TestHttpServer(int sockfd)
{
    std::unique_ptr<char> buffer(new char[BUFFER_SIZE]);

    ssize_t n = recv(sockfd, buffer.get(), BUFFER_SIZE - 1, 0);

    if (n <= 0)
        return;

    //((buffer.get())+n)='\0';
    (buffer.get())[n] = '\0';
    // std::cout<<buffer.get()<<std::endl;

    std::vector<std::string> vline;

    // 请求行: 请求方法 url http版本\r\n
    // 请求报头:key:value\r\nkey:value\r\nkey:value\r\n
    // \r\n
    // 请求正文
    Util::cutString(buffer.get(), "\r\n", &vline);

    // for(auto &iter:vline)
    // {
    //     std::cout<<iter<<std::endl;
    // }
    // std::cout<<"----------------------------------"<<std::endl;

    std::vector<std::string> voneline; // 请求行

    Util::cutString(vline[0], " ", &voneline);

    // for(auto &iter:voneline)
    // {
    //     std::cout<<iter<<std::endl;
    // }

    std::string filepath = ROOT;

    // 获取url
    std::string target = voneline[1];
    if (target == "/")
        target += HOMEPAGE;

    filepath += target;

    std::string content;
    std::ifstream in(filepath);
    if (in.is_open())
    {
        std::string line;
        while (std::getline(in, line))
        {
            content += line;
        }
    }

    // 状态行:http版本 状态码 状态描述
    // 响应报头:key:value\r\nkey:value\r\nkey:value\r\n
    // \r\n
    // 响应正文:

    std::string HttpResponse;
    if (content.empty())
        HttpResponse = "HTTP/1.1 404 NotFound\r\n";
    else
        HttpResponse = "HTTP/1.1 200 OK\r\n";
    HttpResponse += "\r\n";
    HttpResponse += content;

    send(sockfd, HttpResponse.c_str(), HttpResponse.size(), 0);
}

int main(int argc, char *argv[], char *env[])
{
    if (argc != 2)
    {
        std::cout << "\nUsage: " << argv[0] << " port\n"
                  << std::endl;
        exit(1);
    }

    std::unique_ptr<HttpServer> httpServer(new HttpServer(atoi(argv[1]), TestHttpServer));

    httpServer->Start();

    return 0;
}